<template>
  <el-dialog v-model="visible" :title="title" width="780" show-footer show-zoom resize @close="close" :close-on-click-modal="false">
    <template #default>
      <el-form ref="formRef" :model="formData" label-align="right" inline label-width="120" size="default" class="form" label-position="top" :rules="rules">
        <el-form-item label="指标" prop="indicator_type">
          <el-select style="width: 350px" v-model="formData.indicator_type" collapse-tags placeholder="指标" clearable @change="indicatorTypeChange" :disabled="!!formData.id">
            <el-option v-for="item in props.originOption.kpi_indicator_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="期望目标" class="mr-[0]" prop="desired_target">
          <VGroup>
            <template v-if="[1, 3].includes(formData.indicator_type)">
              <el-input style="width: 250px" v-model="formData.desired_target" placeholder="请输入期望目标" @input="desiredTargetChange($event, 1)"></el-input>
              <span style="display: grid" v-show="[1, 3].includes(formData.indicator_type)">
                <el-select style="width: 100px" v-model="formData.currency" placeholder="币种">
                  <el-option label="CNY" value="CNY" />
                  <el-option label="USD" value="USD" />
                </el-select>
              </span>
            </template>
            <template v-else>
              <el-input style="width: 250px" v-model="formData.desired_target" placeholder="请输入期望目标" @input="desiredTargetChange($event, 2)"></el-input>
            </template>
          </VGroup>
        </el-form-item>
        <el-form-item label="时间范围" prop="timeRange">
          <el-date-picker
            v-model="formData.timeRange"
            type="month"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            value-format="YYYY-MM"
            style="width: 350px"
            @change="changeDay"
          />
        </el-form-item>

        <el-form-item label="目标类型" prop="target_type">
          <el-select style="width: 350px" v-model="formData.target_type" collapse-tags placeholder="指标" clearable @change="targetTypeChange">
            <el-option v-for="item in props.originOption.kpi_target_type" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>

        <!-- <template v-if="formData.target_type == 1" > -->
        <el-form-item label="所属部门/人员" prop="department" class="mr-[0]" v-if="formData.target_type == 1">
          <Cascader
            v-model:modelValue="formData.department"
            type="department"
            style="width: 350px"
            @change="getDepartmentUser"
            :disabled="!formData.indicator_type"
            :multiple="false"
            :formItem="{ itemProps: { emitPath: false, checkStrictly: true } }"
          />
        </el-form-item>
        <div v-if="formData.target_type == 1" class="flex">
          <el-form-item label="目标负责人" prop="target_owner">
            <Cascader v-model:modelValue="formData.target_owner" style="width: 350px" :disabled="!formData.indicator_type" />
          </el-form-item>
          <el-form-item>
            <template #label><div class="text-[#fff]">_</div></template>
            <div class="text-[12px]">说明：在用户页面，只有对应负责人才会显示团队目标</div>
          </el-form-item>
        </div>

        <!-- </template> -->

        <el-form-item label="所属部门/人员" prop="department" class="mr-[0]" v-if="formData.target_type == 2">
          <Cascader v-model:modelValue="formData.department" style="width: 350px" @change="departmentChange" :disabled="!formData.indicator_type" />
        </el-form-item>

        <el-table :data="formData.target_values" border style="width: 100%" highlight-current-row height="400">
          <el-table-column prop="name" label="部门/人员" />

          <el-table-column prop="target" label="部门/人员目标" width="200">
            <template #default="{ row }">
              <div class="w-[100%]">
                <div v-if="[1, 3].includes(formData.indicator_type)" class="flex items-center">
                  <el-input class="mr-1 flex-1" v-model="row.target" @change="changeTarget($event, row)" oninput="value=value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, '$1')"></el-input>
                  <div class="w-30">{{ formData.currency }}</div>
                </div>
                <div v-else>
                  <el-input class="mr-1 flex-1" v-model="row.target" @change="changeTarget($event, row)" oninput="value=value.replace(/[^\d]/g, '')"></el-input>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="daily_target" label="日均目标" width="180">
            <template #default="{ row }">
              {{ row.daily_target }}
              <span v-if="[1, 3].includes(formData.indicator_type)"> {{ formData.currency }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="address" label="操作" width="100">
            <template #default="{ row, $index }">
              <el-button type="danger" link @click="handleDelete(row, $index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </template>
    <template #footer>
      <div v-if="handleType == 'view'">
        <el-button @click="close">关闭</el-button>
      </div>

      <div v-else>
        <el-button @click="close">取 消</el-button>
        <el-button type="primary" :loading="loading" @click="save">保 存</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup name="ComModal">
import { createPerformanceIndicator, updatePerformanceIndicator, getPerformanceIndicatorDetail, baseKpi, kpiCreate, kpiEdit } from "../api/index"
import { reactive, ref, toRefs, getCurrentInstance, computed } from "vue"
import { ElMessage, ElSelect } from "element-plus"
import { filterDayApart } from "@/utils/config.js"
// import SelectCurrency from "@/components/Selects/SelectCurrency"
import { deepClone } from "@/utils/index.js"
// 级联配置 选项数据
import Cascader from "@/components/XForm/components/Cascader/index.vue"
const cascaderOpt = ref({})
// 期望目标  改动
const desiredTargetChange = (value, type) => {
  if (type == 1) {
    formData.value.desired_target = value.replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/, "$1")
  } else {
    formData.value.desired_target = value.replace(/[^\d]/g, "")
  }
  blurApportion()
}
const rules = {
  indicator_type: [{ required: true, message: "请选择", trigger: "change" }],
  desired_target: [{ required: true, message: "请选择", trigger: "change" }],
  timeRange: [{ required: true, message: "请选择", trigger: "change" }],
  target_type: [{ required: true, message: "请选择", trigger: "change" }],
  department: [{ required: true, message: "请选择", trigger: "change" }],
  target_owner: [{ required: true, message: "请选择", trigger: "change" }],
}
const departmentChange = ({ value, labels }) => {
  let length = formData.value.target_values.length
  if (value) {
    let targetIds = formData.value.target_values?.map((v) => v.id)
    let data = value.map((v, i) => ({ id: v, name: labels[i], target: 0 }))?.filter((v) => !targetIds.includes(v.id))
    data = data.filter((v) => !v.name.includes("已离职"))
    formData.value.target_values = [...formData.value.target_values, ...data]
    formData.value.target_values = formData.value.target_values.filter((v) => value.includes(v.id))
    formData.value.department = formData.value.target_values.map((v) => v.id)
  } else {
    formData.value.target_values = []
    formData.value.department = []
  }
  // console.log( formData.value.target_values)
  //
  // 初次选择人员
  if (!length) {
    blurApportion()
  }
}

const visible = ref(false)
const loading = ref(false)
const formRef = ref(null)
const emits = defineEmits(["query"])
const props = defineProps({
  originOption: { type: Object, default: () => {} },
})

const data = reactive({
  formData: {},
  title: "新增",
  handleType: null,
  daysApart: 1, // 日期跨度
})
const { formData, title, handleType, daysApart } = toRefs(data)

const statusMap = new Map([
  ["add", "新增"],
  ["edit", "编辑"],
  ["view", "查看"],
  ["copy", "新增"],
])
const open = (type, id) => {
  title.value = statusMap.get(type)
  handleType.value = type
  visible.value = true
  if (id) getDetail(id)
}

const initForm = () => {
  formData.value = { target_values: [] }
}
const getDepartmentUser = ({ value, labels }) => {
  let data = []
  const getDepartment = (list = []) => {
    list.forEach((v) => {
      if (v.organization_type == 1) {
        if (v.id == value[0]) {
          data = v?.sub.filter((v) => v.is_department_head == 1)
        } else {
          getDepartment(v.sub)
        }
      }
    })
  }
  // name target daily_target address
  getDepartment(personnel.value)
  formData.value.target_owner = data.map((v) => v.id)
  // let param = {
  //   value: data.map((v) => v.id),
  //   labels: data.map((v) => v.name),
  // }

  // departmentChange(param)

  // departmentChange({ value, labels })

  // 部门
  // console.log(value)

  formData.value.department = value?.[0]
  // console.log({ value, labels })

  formData.value.target_values = [{ id: value[0], name: labels[0], target: Number(formData.value.desired_target).toFixed(2) }]
  changeTarget("", formData.value.target_values[0])
  // if (formData.value.target_type == 1) {
  //   // blurApportion()
  //   console.log(223344)
  //   formData.value.target_values[0].target = Number(formData.value.desired_target).toFixed(2)
  //   console.log(formData.value)
  // }
}

import cache from "@/plugins/cache"

const personnel = ref([])
onMounted(() => {
  initForm()
  personnel.value = cache.session.getJSON("personnel") || ""
})
import { parseTime } from "@/utils/ruoyi"
const getDetail = async (id) => {
  try {
    const res = await baseKpi(id)
    if (handleType.value == "copy") {
      res.data.timeRange = parseTime(res.data.start_time, "{y}-{m}")
      // res.data.timeRange = [res.data.start_time, res.data.end_time]
      res.data.department = res.data.target_values.map((v) => v.id)
      delete res.data.id
      formData.value = res.data
    } else {
      res.data.timeRange = parseTime(res.data.start_time, "{y}-{m}")
      // res.data.timeRange = [res.data.start_time, res.data.end_time]
      res.data.department = res.data.target_values.map((v) => v.id)
      formData.value = res.data
    }
    changeDay(formData.value.timeRange)
    // console.log(formData.value)
    // 部门
    if (formData.value.target_type == 1) {
      res.data.department = res.data.department[0]
    }
  } catch (e) {
    throw Error(e)
  }
}

// 指标 变动
const indicatorTypeChange = (e) => {
  if ([1, 2, 3, 6].includes(e)) {
    formData.value.currency = "CNY"
  }
  // 清空数据
  formData.value.desired_target = ""
  formData.value.target_values.forEach((item) => {
    item.target = ""
    item.daily_target = ""
  })
}

// 时间范围 变动
const changeDay = async (val) => {
  if (val) {
    const day = filterDayApart(`${val}-01`, getLastDayOfMonth(val))
    daysApart.value = day + 1

    // blurApportion()
  }
}
const targetTypeChange = (e) => {
  formData.value.department = []
  formData.value.target_values = []
  formData.value.target_owner = []
}
// 个人目标 变动
const changeTarget = async (val, row) => {
  if ([1, 2, 3, 6].includes(formData.value.indicator_type)) {
    const average = (row.target / (daysApart.value || 1)).toFixed(2)
    row.daily_target = average
    calculateSum()
  } else {
    row.daily_target = row.target
  }
}
// 个人目标 删除行
const handleDelete = async (row, index) => {
  formData.value.target_values = formData.value.target_values.filter((v) => v.id != row.id)
  formData.value.department = formData.value.department.filter((v) => v != row.id)
  // blurApportion()
  calculateSum()
}
// 个人目标 变动 计算期望目标
const calculateSum = () => {
  formData.value.desired_target = formData.value.target_values.reduce((pre, cur) => {
    return pre + Number(cur.target || 0)
  }, 0)
}

// 修改期望目标 分摊
const blurApportion = async (val) => {
  // 期望目标为0
  if (formData.value.desired_target == 0) {
    formData.value.desired_target = ""
    return
  }
  // 未选择 部门/人员
  if (formData.value.target_values?.length == 0) {
    return
  }
  // if (formData.value.indicator_type == 2) {
  //   return
  // }
  // 指标类型 币种
  if ([1, 3].includes(formData.value.indicator_type)) {
    const minuteAverage = (formData.value.desired_target / formData.value.target_values?.length).toFixed(2)
    const average = (minuteAverage / (daysApart.value || 1)).toFixed(2)
    formData.value.target_values.forEach((i) => {
      i.target = minuteAverage
      i.daily_target = average
    })
  } else {
    // 订单量
    let result = formData.value.desired_target % formData.value.target_values?.length
    const minuteAverage = Math.floor(formData.value.desired_target / formData.value.target_values?.length)
    const average = (minuteAverage / (daysApart.value || 1)).toFixed(2)
    formData.value.target_values.forEach((i) => {
      i.target = minuteAverage
      i.daily_target = average
    })
    formData.value.target_values[0].target = Number(result) + Number(minuteAverage)

    // 指标类型 百分比
    // formData.value.target_values.forEach((i) => {
    //   i.target = formData.value.desired_target
    //   i.daily_target = formData.value.desired_target
    // })
  }
}

const getLastDayOfMonth = (date) => {
  let year = date.split("-")[0]
  let month = date.split("-")[1]
  return parseTime(new Date(year, month, 0), "{y}-{m}-{d}")
}
const save = async () => {
  await formRef.value.validate((valid, fields) => {
    if (valid) {
      formData.value.start_time = formData.value.timeRange + "-01 00:00:00"
      formData.value.end_time = getLastDayOfMonth(formData.value.timeRange) + " 23:59:59"
      let user = formData.value.target_values.find((v) => v.target == 0)
      if (user?.name) {
        return ElMessage({ showClose: true, message: `${user?.name} 目标值能不能为0！`, type: "warning" })
      }
      if (!formData.value.id) {
        kpiCreate(formData.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits("query")
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      } else {
        kpiEdit(formData.value)
          .then((res) => {
            ElMessage.success(res.message)
            emits("query")
            close()
          })
          .finally((e) => {
            loading.value = false
          })
      }
    } else {
    }
  })
}

const close = () => {
  initForm()
  formRef.value.clearValidate()
  visible.value = false
}
defineExpose({ open })
</script>
<style lang="scss" scoped></style>
